package com.bootcamp.servlet.util;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Timestamp;
import java.util.*;

/**
 * @program: wrok-1101
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-03 15:20
 **/

public class MultiFormUserInfoUtils {
    private MultiFormUserInfoUtils() {
    }

    private static final int MAX_SIZE_BYTES = 10 * 1024 * 1024;

    public static Map multiFormToMap(HttpServletRequest request) {

        // 获取 FileUpload
        ServletFileUpload fileUpload = new ServletFileUpload();
//        fileUpload.setFileSizeMax(MAX_SIZE_BYTES);
        // map存储变量名
        Map<String, List<String>> params = new HashMap<>();
        // 解析 request
        try {
            FileItemIterator itemIterator = fileUpload.getItemIterator(request);
            while (itemIterator.hasNext()) {
                FileItemStream item = itemIterator.next();
                if (item.isFormField()) {
                    opFormField(item, params);
                } else {
                    opFileField(item, params, request);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return params;
    }

    private static void opFileField(FileItemStream item, Map<String, List<String>> params, HttpServletRequest request) {
        String key = item.getFieldName();
        try {

            // 确定存储图片名字 及 位置
            String uuid = UUID.randomUUID().toString();
            String fileName = uuid + "-" + item.getName();
            String hashDir = Integer.toHexString(fileName.hashCode());
            String fileDir = "resources/image/" + hashDir.substring(0, 4) + "/" + hashDir.substring(4) + "/" + fileName;

            String basePath = request.getServletContext().getRealPath(fileDir);
            System.out.println(basePath);
            // 创建相关文件夹
            File imgDest = new File(basePath);
            File parentFile = imgDest.getParentFile();
            if (!parentFile.exists() || parentFile.isFile()) {
                parentFile.mkdirs();
            }
            // 输入流读入输出流
            FileOutputStream outputStream = new FileOutputStream(imgDest);
            InputStream inputStream = item.openStream();
            byte[] bytes = new byte[1024];
            int length;
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            inputStream.close();
            outputStream.close();
            // 添加到map
            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<>();
                params.put(key, values);
            }
            values.add(fileDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void opFormField(FileItemStream item, Map<String, List<String>> params) {
        String key = item.getFieldName();
        try {
            InputStream inputStream = item.openStream();
            String value = Streams.asString(item.openStream(), "utf-8");
            // 判断是否已经存在key
            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<String>();
                params.put(key, values);
            }
            if (values.contains(value)) {
                return;
            }
            values.add(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
